/*
 * @lc app=leetcode.cn id=54 lang=javascript
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  if (!matrix.length || !matrix[0].length) {
    return [];
  }

  const result = [];
  let top = 0;
  let bottom = matrix.length - 1;
  let left = 0;
  let right = matrix[0].length - 1;

  while (true) {
    // 左->右
    for (let i = left; i <= right; i++) {
      result.push(matrix[top][i]);
    }
    if (++top > bottom) break;
    // 上->下
    for (let i = top; i <= bottom; i++) {
      result.push(matrix[i][right]);
    }
    if (left > --right) break;
    // 右->左
    for (let i = right; i >= left; i--) {
      result.push(matrix[bottom][i]);
    }
    if (top > --bottom) break;
    // 下->上
    for (let i = bottom; i >= top; i--) {
      result.push(matrix[i][left]);
    }
    if (++left > right) break;
  }

  return result;
};
// @lc code=end
